package com.lg.atp.controller;

import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lg.atp.common.Constants;
import com.lg.atp.entity.TblDeviceInfo;
import com.lg.atp.service.IDeviceInfoService;
import com.lg.atp.service.ScriptService;
import com.lg.atp.utils.DeviceConstants;
import com.lg.atp.utils.XmlUtils;
import com.lg.atp.ws.WSClient;
import com.lg.atp.xml.XmlBean;

@RestController
@RequestMapping("device")
public class DeviceController {

	private static final Log log = LogFactory.getLog(DeviceController.class);
	
	@Autowired
	private IDeviceInfoService deviceInfoService;
	@Autowired
	private ScriptService scriptService;
	
	private @Value("${relibleMaster}") String relibleMaster;
	@GetMapping("index")
	public ModelAndView toIndex() {
		ModelAndView view = new ModelAndView();
		view.setViewName("deviceList");
		return view;
	}
	
	@PostMapping("givebackDevice")
	public Map<String,Object> givebackDevice(long deviceId) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			TblDeviceInfo tblDeviceInfo = deviceInfoService.geTblDeviceInfoById(deviceId);
			if(!"ios".equals(tblDeviceInfo.getPlatform())) {
				WSClient client = new WSClient(relibleMaster);
				client.controlDevicesById(tblDeviceInfo.getUdid(),"stop");
			}
			tblDeviceInfo.setDeviceStatus(DeviceConstants.DEVICE_STATUS_VALID);
			deviceInfoService.updateDevice(tblDeviceInfo);
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error("归还设备失败"+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "归还设备失败");
		}
		return result;
	}
	
	@PostMapping("laylist")
	public Map<String,Object> layList(String serialNumber,String model,String brand,Integer pageIndex,Integer pageSize){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			
			 Map<String,Object> map = new HashMap<String,Object>();
			 map.put("serialNumber", serialNumber);
			 map.put("brand", brand);
			 map.put("model", model);
			 map.put("pageIndex", pageIndex);
			 map.put("pageSize", pageSize);
		     PageInfo<TblDeviceInfo> list = deviceInfoService.getDeviceByPara(map);
		     result.put("data", list);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("获取设备列表失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "获取设备列表失败");
		}
		return result;
	}
	@PostMapping("showDevice")
	public Map<String,Object> showDevice(Long deviceId,Long caseId,int reuse) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			TblDeviceInfo tblDeviceInfo;
			synchronized (DeviceController.class) {
				deviceInfoService.saveDeviceList4Macaca();
				tblDeviceInfo = deviceInfoService.geTblDeviceInfoById(deviceId);
				if (!DeviceConstants.DEVICE_STATUS_VALID.equals(tblDeviceInfo.getDeviceStatus())) {
					result.put("status", Constants.RETURN_FAIL);
					result.put("errorMsg", "当前设备不可用");
					return result;
				}
				
			}
			WSClient client = new WSClient(relibleMaster);
			String webSocketPort = client.controlDevicesById(tblDeviceInfo.getUdid(),"run");
			result.put("webSocketPort", webSocketPort);
			result.put("webSocketIP", tblDeviceInfo.getSlaveIp());
			tblDeviceInfo.setDeviceStatus(DeviceConstants.DEVICE_STATUS_USING);
			deviceInfoService.updateDevice(tblDeviceInfo);
			scriptService.recording(caseId, deviceId,reuse);
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error("启动设备失败"+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "启动设备失败");
		}
		return result;
	}
	
	@PostMapping("tapHold")
	public String tapHold(Integer x,Integer y,Integer holdTime) throws IOException {
		URL oracle;
		try {
			oracle = new URL("http://localhost:8080/test/tapHold/?x=" + x + "&y=" + y+ "&duration=" +holdTime);
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	            String inputLine = null;
	            while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	            }
	            System.out.println(json.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		return "success";
	}
	
	@PostMapping("swipe")
	public String swipe(Integer startX,Integer startY,Integer endX,Integer endY) throws IOException {
		URL oracle;
		try {
			oracle = new URL("http://localhost:8080/test/swipe?fromX=" + startX + "&fromY=" + startY + "&toX=" + endX + "&toY=" + endY + "&duration=" + 0.08);
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	            String inputLine = null;
	            while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	            }
	            System.out.println(json.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		return "success";
	}
	
	@PostMapping("tap")
	public String tap(Integer x,Integer y,boolean recordFlag) throws Exception {
		URL oracle;
		String str="";
		String beanName="";
		String newString = "";
		try {
	        if(recordFlag){
	        		oracle = new URL("http://localhost:8080/test/source");
				StringBuilder jsonSource = new StringBuilder();
				URLConnection ycSource = oracle.openConnection();
				BufferedReader inSource = new BufferedReader(new InputStreamReader(
						ycSource.getInputStream(),"utf-8"));//防止乱码
		        String inputSourceLine = null;
		        while ((inputSourceLine = inSource.readLine()) != null) {
		            		jsonSource.append(inputSourceLine);
		        }
		        JSONObject jsStr = JSONObject.parseObject(jsonSource.toString());
				System.out.println(jsStr.get("value"));
				str =jsStr.get("value").toString();
//				System.out.println(str);
				
				newString = str.replace("children", "nodes");
				XmlUtils xmlutil = new XmlUtils();
				List<XmlBean> list = xmlutil.parseXmlToBean(str);
				for(int i=0;i<list.size();i++) {
					Integer px1 = Integer.parseInt(list.get(i).getX());
					Integer py1 = Integer.parseInt(list.get(i).getY());
					Integer px2 = Integer.parseInt(list.get(i).getWidth());
					Integer py2 = Integer.parseInt(list.get(i).getHeight());
					Rectangle rect = new Rectangle(px1,py1,px2,py2);
					if(rect.contains(x,y)&&!"XCUIElementTypeApplication".equals(list.get(i).getType())
							&&!"XCUIElementTypeOther".equals(list.get(i).getType())
							&&!"XCUIElementTypeWindow".equals(list.get(i).getType())
							&&"true".equals(list.get(i).getEnabled())&&"true".equals(list.get(i).getVisible())
							&&!"0".equals(list.get(i).getX())&&!"0".equals(list.get(i).getY())) {
						if(list.get(i).getName()==null) {
							beanName = list.get(i).getType()+"[1]";
							System.out.println("this is beanName:"+beanName);
						}else {
							beanName = list.get(i).getName();
						}
					}
					rect = null;
				}
	    		}   
	        oracle = new URL("http://localhost:8080/test/tap/?x=" + x + "&y=" + y);
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	        String inputLine = null;
	        while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	         }
	        
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		System.out.println("this is :"+beanName);
		return beanName;
	}
	
	
	@PostMapping("home")
	public String home() throws IOException {
		URL oracle;
		try {
			oracle = new URL("http://localhost:8080/test/home");
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	            String inputLine = null;
	            while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	            }
	            System.out.println(json.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		return "success";
	}
	
	
	public String exitMincap() throws IOException {
		URL oracle;
		try {
			oracle = new URL("http://localhost:8080/test/exitMincap");
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	            String inputLine = null;
	            while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	            }
	            System.out.println(json.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		return "success";
	}
	public String exitWDA() throws IOException {
		URL oracle;
		try {
			oracle = new URL("http://localhost:8080/test/exitWDA");
			StringBuilder json = new StringBuilder();
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
	                    yc.getInputStream(),"utf-8"));//防止乱码
	            String inputLine = null;
	            while ((inputLine = in.readLine()) != null) {
	                json.append(inputLine);
	            }
	            System.out.println(json.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "faild";
		}
		return "success";
	}
	
	 public double Multiply(double px0, double py0, double px1, double py1,  
	            double px2, double py2) {  
	        return ((px1 - px0) * (py2 - py0) - (px2 - px0) * (py1 - py0));  
	    }  
	

}
